package com.yosaa.back.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yosaa.back.entity.AnalysisResult;
import com.yosaa.back.entity.ScoringStandard;
import com.yosaa.back.entity.UserInfo;
import com.yosaa.back.entity.vo.MoonshotResponse;
import com.yosaa.back.mapper.AnalysisResultMapper;
import com.yosaa.back.service.IAnalysisResultService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yosaa.back.service.IScoringStandardService;
import com.yosaa.back.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 分析结果表，存储AI分析模块生成的健康评估和个性化建议 服务实现类
 * </p>
 *

 */
@Service
public class AnalysisResultServiceImpl extends ServiceImpl<AnalysisResultMapper, AnalysisResult> implements IAnalysisResultService {
    @Value("${moonshot.api.key}")
    private String apiKey;

    @Autowired
    private IUsersService usersService;
    @Autowired
    private IScoringStandardService scoringStandardService;
    private static String sysPrompt = "请根据《国家学生体质健康标准》解析以下学生的体测成绩，生成一份健康分析报告, 表述需要严谨准确。报告应包括：\n" +
            "健康状态总结（Health Status），对学生的体质状况进行全面评价；\n" +
            "针对运动的详细建议（200字左右），帮助学生改善健康状况。" +
            "使用Jsong格式返回，例如：\n" +
            "{" +
            "  \"health_status\": \"根据《国家学生体质健康标准》，小明的总体体测成绩为63.07分，等级为及格。耐力跑和引体向上表现优秀，显示出良好的心肺功能和上肢力量；体重指数在正常范围，表明体型健康。但50米跑表现较弱，爆发力和速度方面有待提高。总体来看，小明的身体素质较为均衡，但仍有提升空间。\",\n" +
            "  \"suggestions\": \"针对小明的体测结果，建议在运动方面加强短跑训练，比如每周进行2-3次冲刺跑训练，每次20-30分钟，以提高爆发力和速度。同时，保持耐力跑和力量训练的习惯，每周进行2次长跑（5-8公里）和2次引体向上训练。在饮食方面，确保每日摄入足够的蛋白质（如鸡蛋、鱼肉和豆制品）来促进肌肉修复，适量增加碳水化合物（如全谷物、燕麦）以提供能量，避免高脂肪、高糖食品。此外，建议每天保持7-8小时的睡眠，规律作息，增强身体恢复能力。长期坚持科学的运动和饮食计划，有助于提升综合体能水平。\"\n" +
            "}" + "\n 实际生成的内容不可以和样例相似";


    public void aiAnalysis(Integer userId) {
        UserInfo userInfo = usersService.getById(userId);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        ScoringStandard userScore = scoringStandardService.getOne(queryWrapper);

        if (userInfo != null && userScore != null) {
            String userPrompt = "用户名" + userInfo.getUsername() + "，性别：" + userInfo.getSex() + "，年级：" + userInfo.getGrade() + "\n";
            userPrompt += "以下是根据《国家学生体质健康标准》计算的体测成绩分数：\n" +
                    "立定跳远分数：" + userScore.getScore1() + "\n" +
                    "耐力跑（男：1000m;女：800m）分数：" + userScore.getScore2() + "\n" +
                    "男：引体向上;女：仰卧起坐分数：" + userScore.getScore3() + "\n" +
                    "50米跑分数：" + userScore.getScore4() + "\n" +
                    "坐位体前屈分数：" + userScore.getScore5() + "\n" +
                    "体重指数：" + userScore.getScore6() + "\n" +
                    "肺活量分数：" + userScore.getScore7() +  "\n" +
                    "根据权重占比最终得分：" + userScore.getScore() + "，等级：" + userScore.getGrade();
            getKiMiData(userPrompt,userId);
        }
    }


    public void getKiMiData(String userPrompt, Integer userId) {
        String url = "https://api.moonshot.cn/v1/chat/completions";

        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);

        Map<String, Object> requestBody = new HashMap<>();

        requestBody.put("model", "moonshot-v1-8k");


        Map<String, String> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");


        if (StringUtils.isEmpty(sysPrompt)) {
            new Exception("提示词不能为空，已跳过");
        } else {
            systemMessage.put("content", sysPrompt);
            Map<String, String> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", userPrompt);

            List<Map<String, String>> messages = Arrays.asList(systemMessage, userMessage);
            requestBody.put("messages", messages);
            requestBody.put("temperature", 0.3);
            requestBody.put("stream", false);
            Map<String, String> format = new HashMap<>();
            format.put("type", "json_object");
            requestBody.put("response_format", format);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            String responseBody = response.getBody();

            MoonshotResponse moonshotResponse = JSON.parseObject(responseBody, MoonshotResponse.class);

            MoonshotResponse.Choice choice = moonshotResponse.getChoices().get(0);

            String jsonContent = choice.getMessage().getContent();
            if (!"stop".equals(choice.getFinishReason())) {
                System.out.println("内容过长未解析完成");
            }
            System.out.println(jsonContent);

            JSONObject jsonObject = JSON.parseObject(jsonContent);
            String healthStatus = jsonObject.getString("health_status");
            String suggestions = jsonObject.getString("suggestions");

            AnalysisResult analysisResult = new AnalysisResult();
            analysisResult.setUserId(userId);
            analysisResult.setHealthStatus(healthStatus);
            analysisResult.setSuggestions(suggestions);
            analysisResult.setAnalysisDate(LocalDateTime.now());
            save(analysisResult);
        }

    }

}
